var express = require('express');
var router = express.Router();
var md5 = require("md5");
var typeDAO = require("../bin/db/typeDAO.js");
var goodsDAO = require("../bin/db/goodsDAO.js");
var userDAO = require("../bin/db/userDAO.js");
var carDAO = require("../bin/db/carDAO.js");
var ccap = require("ccap");
var captcha = ccap({
  width: 220,
  height: 60,
  offset: 40,
  quality: 100,
  fontsize: 40,
  generate: function () {
    var sourceStr = "123456789";
    var text = "";
    for (var i = 0; i < 5; i++) {
      var index = Math.floor(Math.random() * sourceStr.length);
      var che = sourceStr[index];
      text += che;
    }
    return text;
  }
});
// 商品上传
var obj = [];
var multer = require("multer");
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/images')
  },
  filename: function (req, file, cb) {
    var ind = file.mimetype.lastIndexOf("/");
    var suffix = file.mimetype.substr(ind + 1);
    var filename = file.fieldname + '-' + Date.now() + "." + suffix;
    req[file.fieldname] = filename;
    var img = req[file.fieldname];
    for (var i = 0; i < img.length; i++) {
      obj = obj + img[i];
    }
    cb(null, filename);
  }
})
var upload = multer({ storage: storage })
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});
router.get("/user", function (req, res) {
  var list = [
    { img: '/images/1.jpg' },
    { img: '/images/2.jpg' },
    { img: '/images/3.jpg' }
  ]
  res.json({ err: 0, list: list });
});
router.get("/navimg", function (req, res) {
  var img = [
    { img: "/images/nav1.jpg", title: "商品分类", ps: "/sort", pss: "/sort" },
    { img: "/images/nav2.jpg", title: "登录注册", ps: "/login", pss: "/myself" },
    { img: "/images/nav3.jpg", title: "卡券激活", ps: "/juan", pss: "/juan" },
    { img: "/images/nav4.jpg", title: "中秋送礼", ps: '/goods/smallsort/goodslist/' + 55, pss: '/goods/smallsort/goodslist/' + 55 },
    { img: "/images/nav5.jpg", title: "配送售后", ps: "/peisong", pss: "/peisong" }
  ]
  res.json({ err: 0, list: img });
})
router.get("/captcha", function (req, res) {
  // captcha.get()，生成验证码.结果是一个数组,数组中第一个元素是验证码的文本,第二个元素是验证码图片(buffer)。
  var arr = captcha.get();
  req.session.captcha = arr[0];
  // 本接口返回一个图片,所以要将响应体类型设置为图片
  res.set("Content-Type", "image/jpeg");
  res.send(arr[1]);
})
// 用户注册接口
router.post("/regist", function (req, res) {
  var reg = /1[3|5|7|8|9]\d{9}$/;
  if (!reg.test(req.body.username)) {
    res.json({ err: 1, msg: "用户名不合法" });
    return;
  }
  var ref = /^[a-zA-Z0-9_-]{4,16}$/;
  if (!ref.test(req.body.psw)) {
    res.json({ err: 2, msg: "您的密码不合规则" });
    return;
  }
  if (req.body.captcha != req.session.captcha) {
    res.json({ err: 3, msg: "验证码错误" });
    return;
  }
  userDAO.findOne({ username: req.body.username })
    .then(data => {
      if (data) {
        res.json({ err: 3 ,msg:"用户已存在"});
      } else {
        var u = new userDAO({
          username: req.body.username,
          psw: req.body.psw
        });
        u.psw = md5(u.psw);
        u.save()
          .then(data => {
            req.session.user = data;
            res.json({ err: 0, msg: "注册成功" });
          })
      }
    })


})
// 请求登录
router.post("/login", (req, res) => {
  userDAO.findOne({ username: req.body.username })
    .exec(function (err, data) {
      if (!data) {
        res.json({ err: 1, msg: "没有此用户" });
        return;
      }
      if (req.body.captcha != req.session.captcha) {
        res.json({ err: 3, msg: "验证码错误" });
        return;
      }
      else if (md5(req.body.psw) == data.psw) {
        req.session.user = data;
        res.json({ err: 0, msg: "登录成功" })
      } else {
        res.json({ err: 2, msg: "账号密码错误" })
      }

    })
})
// 判断是否登录接口
router.post("/islogin", (req, res) => {
  if (req.session.user) {
    userDAO.findOne({ _id: req.session.user._id })
      .then(data => {
        req.session.user = data;
        var isLogin = {
          isLogin: true,
          data: data
        }
        res.json({ isLogin });
      })
  } else {
    var isLogin = {
      isLogin: false
    }
    res.json({ err: 1, isLogin });
  }
})
// myself页面请求图片
router.get("/requestpic", (req, res) => {
  var img = [
    { imgs: "/images/mem-base.jpg" },
    { imgs: "/images/b6c91f4dd42df8d18ff7bc9afce84dcd0c6b4319.jpg" }
  ]
  res.json({ err: 0, list: img })
})
// 退出接口
router.post("/tuichu", (req, res) => {
  if (req.session.user) {
    req.session.user = "";
    res.json({ err: 0, msg: "退出成功" });
  }

})
// 卡劵接口
router.get("/kajuanpic", (req, res) => {
  var img = [
    { img: "/images/logoA.png" },
    { img: "/images/button1.png" },
    { img: "/images/button2.png" }
  ]
  res.json({ err: 0, msg: img })
})
// 商品上传接口
router.post("/goods/upload", upload.array("image"), (req, res) => {
  var g = new goodsDAO(req.body);
  g.save()
    .then(data => {
      var imgobj = [];
      imgobj = obj.split("i");
      for (i = imgobj.length - 1; i > 0; i--) {
        data.pic.push("/images/i" + imgobj[i]);
      }
      obj = [];
      data.save(function (err) {
        if (!err) {
          typeDAO.findOne({ bigtype: req.body.bigtype })
            .exec(function (err, data) {
              if (data) {
                for (var i = 0; i < data.smalltype.length; i++) {
                  if (data.smalltype[i] == req.body.smalltype) {
                  } else {
                    data.smalltype.push(req.body.smalltype);
                    data.save();
                    res.json({ err: 0, msg: "添加成功" });
                    return;
                  }
                }
              } else {
                var smalltypes = [];
                smalltypes.push(req.body.smalltype)
                var u = new typeDAO({
                  bigtype: req.body.bigtype,
                  smalltype: smalltypes
                });
                u.save()
                  .then(data => {
                    res.json({ err: 0, msg: "添加成功" });
                  })
              }
            })
        }
      })
    })
})
// 首页商品图片请求
router.post("/hot", (req, res) => {
  var img = [
    { imgs: "/images/4.jpg" },
    { imgs: "/images/5.jpg" },
    { imgs: "/images/6.jpg" },
    { imgs: "/images/7.jpg" },
    { imgs: "/images/8.jpg" },
    { imgs: "/images/9.jpg" },
    { imgs: "/images/10.jpg" },
    { imgs: "/images/11.jpg" },
    { imgs: "/images/12.jpg" },
    { imgs: "/images/13.jpg" },
    { imgs: "/images/14.jpg" },
    { imgs: "/images/15.jpg" },
    { imgs: "/images/16.jpg" },
    { imgs: "/images/17.jpg" },
    { imgs: "/images/18.jpg" },
    { imgs: "/images/12.png" },
    { imgs: "/images/13.png" },
    { imgs: "/images/14.png" }
  ]
  res.json({ err: 0, img })
})
// 首页查询所有水果
router.get("/goods", (req, res) => {
  // console.log(req.query.i)
  goodsDAO.find()
  .skip(6*req.query.i)
  .limit(6)
    .then(data => {
      res.json({ err: 0, data });
    })
})
// 大分类页面
router.post("/goods/sortrequest", (req, res) => {
  typeDAO.find()
    .then(data => {
      res.json({ err: 0, data })
    })
})
// 小分类页面
router.post("/smallsort/request", (req, res) => {
  // console.log(req.body.a);
  typeDAO.findOne({ _id: req.body.a })
    .then(data => {
      res.json({ err: 0, msg: data })
    })
})
// 商品列表请求
router.post("/goodslist", (req, res) => {
  // console.log(req.body.a)
  if (req.body.a == "55") {
    var p = "礼盒";
    goodsDAO.find({ goodsname: { $regex: p } })
      .then(data => {
        res.json({ err: 0, msg: data });
        return;
      })
  } else {
    if (req.body.a == "33") {
      goodsDAO.find()
        .then(data => {
          res.json({ err: 0, msg: data });
          return;
        })
    } else {
      goodsDAO.find({ smalltype: req.body.a })
        .then(data => {
          res.json({ err: 0, msg: data })
        })
    }
  }

})
// 按关键字查询
router.post("/search", (req, res) => {
  // console.log(req.body)
  var p = req.body.params.word;
  // console.log(p);
  goodsDAO.find({ goodsname: { $regex: p },smalltype:req.body.params.a})
    .then(data => {
      // console.log(data);
      res.json({ err: 0, data })
    })
})
// 商品详情页
router.post("/goodsdetails", (req, res) => {
  goodsDAO.findOne({ _id: req.body.a })
    .then(data => {
      res.json({ err: 0, msg: data })
    })
})
// 排序
router.post("/goods/sort", (req, res) => {
  if (req.body.b == "55") {
    var p = "礼盒";
    goodsDAO.find({ goodsname: { $regex: p } }).sort({ "goodsprice": req.body.a })
      .then(data => {
        res.json({ err: 0, msg: data })
      })
  } else {
    if (req.body.b == "33") {
      goodsDAO.find().sort({ "goodsprice": req.body.a })
        .then(data => {
          res.json({ err: 0, msg: data });
          return;
        })
    } else {
      goodsDAO.find({ smalltype: req.body.b }).sort({ "goodsprice": req.body.a })
        .then(data => {
          res.json({ err: 0, msg: data })
        })
    }
  }


})
// 销量
router.post("/goods/number", (req, res) => {
  if (req.body.b == "55") {
    var p = "礼盒";
    goodsDAO.find({ goodsname: { $regex: p } }).sort({ "goodsnumber": req.body.a })
      .then(data => {
        res.json({ err: 0, msg: data });
        return;
      })
  } else {
    if (req.body.b == "33") {
      goodsDAO.find().sort({ "goodsnumber": req.body.a })
        .then(data => {
          res.json({ err: 0, msg: data })
        })
    } else {
      goodsDAO.find({ smalltype: req.body.b }).sort({ "goodsnumber": req.body.a })
        .then(data => {
          res.json({ err: 0, msg: data })
        })
    }
  }

})
// 添加购物车
router.post("/goods/add", (req, res) => {
  // console.log(req.body)
  if (!req.session.user) {
    res.json({ err: 1, msg: "请先登录" })
    return;
  } else {
    carDAO.findOne({ goodsid: req.body.msg._id, userid: req.session.user._id })
      .then(data => {
        if (data) {
          res.json({ err: 0, msg: "请勿重复添加" });
          return;
        } else {
          var u = new carDAO({
            userid: req.session.user._id,
            goodsid: req.body.msg._id,
            goodsname: req.body.msg.goodsname,
            goodsprice: req.body.msg.goodsprice,
            goodsnumber: req.body.msg.goodsnumber,
            goodsarea: req.body.msg.goodsarea,
            bigtype: req.body.msg.bigtype,
            smalltype: req.body.msg.smalltype,
            pic: req.body.msg.pic,
            count: req.body.count
          })
          u.save();
          res.json({ err: 0, msg: "添加成功" })
        }
      })
  }
})
// 购物车请求商品
router.post("/goods/car", (req, res) => {
  if (!req.session.user) {
    res.json({ err: 1 })
  } else {
    carDAO.find({ userid: req.session.user._id })
      .then(data => {
        res.json({ err: 0, data })
      })
  }
})
// 购物车删除接口
router.post("/edit/remove", (req, res) => {
  carDAO.remove({ _id: req.body._id })
    .then(data => {
      res.json({ err: 0, msg: "删除成功" })
    })
})
// 购物车数量修改接口
router.post("/updata", (req, res) => {
  // console.log(req.body)
  carDAO.update({ userid: req.session.user._id, _id: req.body._id }, { count: req.body.count }, function (err) {
    if (!err) {
      carDAO.find({ userid: req.session.user._id })
        .then(data => {
          res.json({ err: 0, data });
        })
    }
  })

})
module.exports = router;
